<template>
  <el-dialog
    title="申请换题"
    :visible.sync="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-alert
        :type="alertType"
        :closable="false"
        style="margin-bottom: 20px;"
      >
        <div style="font-size: 13px; line-height: 1.6;">
          <strong>{{ alertTitle }}</strong><br/>
          • 请确认您当前已被录取的题目信息<br/>
          <template v-if="isSameTeacher">
            • 您选择的是同一教师的题目，只需该教师审核一次<br/>
            • 教师同意后将立即完成换题
          </template>
          <template v-else>
            • 您选择的是不同教师的题目，需要两位教师都同意<br/>
            • 变更成功后原题目将被释放
          </template>
        </div>
      </el-alert>

      <el-form-item label="当前题目" v-if="currentTopic">
        <el-input :value="currentTopic.topicTitle" disabled>
          <template slot="prepend">{{ currentTopic.teacherName }}</template>
        </el-input>
      </el-form-item>

      <el-form-item label="新题目" prop="newTopicId">
        <el-select
          v-model="form.newTopicId"
          placeholder="请选择要换到的题目"
          filterable
          style="width: 100%;"
          @change="handleTopicChange"
        >
          <el-option
            v-for="topic in availableTopics"
            :key="topic.topicId"
            :label="topic.title"
            :value="topic.topicId"
            :disabled="topic.currentStudents >= topic.maxStudents"
          >
            <span style="float: left">{{ topic.title }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ topic.teacherName }} | 
              {{ topic.currentStudents }}/{{ topic.maxStudents }}人
              <el-tag v-if="topic.currentStudents >= topic.maxStudents" type="info" size="mini" style="margin-left: 5px;">已满</el-tag>
              <el-tag v-else-if="isSameTeacherAsTopic(topic)" type="success" size="mini" style="margin-left: 5px;">同教师</el-tag>
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="新题目教师" v-if="selectedTopic">
        <el-input :value="selectedTopic.teacherName" disabled>
          <template slot="append" v-if="isSameTeacher">
            <el-tag type="success" size="mini">与当前教师相同</el-tag>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="新题目简介" v-if="selectedTopic">
        <el-input
          type="textarea"
          :value="selectedTopic.description"
          :rows="3"
          disabled
        />
      </el-form-item>

      <el-form-item label="变更理由" prop="changeReason">
        <el-input
          type="textarea"
          v-model="form.changeReason"
          placeholder="请详细说明您申请换题的理由（必填）"
          :rows="4"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { submitChangeRequest } from "@/api/system/topicChangeRequest";
import { listMyApplications } from "@/api/system/application";
import { listApprovedTopic } from "@/api/system/topic";

export default {
  name: "SubmitDialog",
  data() {
    return {
      dialogVisible: false,
      submitLoading: false,
      // 表单
      form: {
        oldTopicId: null,
        newTopicId: null,
        changeReason: ''
      },
      // 当前录取的题目
      currentTopic: null,
      // 可选题目列表
      availableTopics: [],
      // 选中的新题目
      selectedTopic: null,
      // 表单校验
      rules: {
        newTopicId: [
          { required: true, message: "请选择新题目", trigger: "change" }
        ],
        changeReason: [
          { required: true, message: "请填写变更理由", trigger: "blur" },
          { min: 10, message: "变更理由至少10个字", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    /** 判断是否是同一个教师 */
    isSameTeacher() {
      if (!this.currentTopic || !this.selectedTopic) {
        return false;
      }
      return this.currentTopic.teacherId === this.selectedTopic.teacherId;
    },
    /** 提示框类型 */
    alertType() {
      if (!this.selectedTopic) {
        return 'warning';
      }
      return this.isSameTeacher ? 'info' : 'warning';
    },
    /** 提示框标题 */
    alertTitle() {
      if (!this.selectedTopic) {
        return '⚠️ 温馨提示';
      }
      return this.isSameTeacher ? '💡 同教师内换题' : '⚠️ 跨教师换题';
    }
  },
  methods: {
    /** 打开对话框 */
    open() {
      this.dialogVisible = true;
      this.getCurrentTopic();
      this.getAvailableTopics();
    },
    /** 获取当前录取的题目 */
    getCurrentTopic() {
      listMyApplications().then(response => {
        // 过滤出已录取的申请
        const acceptedApp = response.data.find(app => app.status === '已录取');
        if (acceptedApp) {
          this.currentTopic = {
            topicId: acceptedApp.topicId,
            topicTitle: acceptedApp.topicTitle,
            teacherName: acceptedApp.teacherName,
            teacherId: acceptedApp.teacherId  // 需要教师ID来判断是否同一教师
          };
          this.form.oldTopicId = acceptedApp.topicId;
        } else {
          this.$modal.msgError("您还未被任何题目录取");
          this.dialogVisible = false;
        }
      });
    },
    /** 获取可选题目列表 */
    getAvailableTopics() {
      // 查询所有已通过审核的题目
      listApprovedTopic({ pageNum: 1, pageSize: 999 }).then(response => {
        // 过滤：1.不是当前题目 2.状态是开放 3.有名额
        this.availableTopics = response.rows.filter(topic => 
          topic.topicId !== this.form.oldTopicId &&
          topic.status === '开放' &&
          topic.currentStudents < topic.maxStudents
        );
      });
    },
    /** 判断某个题目是否与当前教师相同 */
    isSameTeacherAsTopic(topic) {
      if (!this.currentTopic) {
        return false;
      }
      return this.currentTopic.teacherId === topic.teacherId;
    },
    /** 题目选择改变 */
    handleTopicChange(topicId) {
      this.selectedTopic = this.availableTopics.find(t => t.topicId === topicId);
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const confirmMsg = this.isSameTeacher
            ? '您正在申请同一教师内换题，教师同意后将立即完成换题。确认提交吗？'
            : '您正在申请跨教师换题，需要两位教师都同意才能完成。确认提交吗？';
          
          this.$confirm(confirmMsg, '确认提交', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.submitLoading = true;
            submitChangeRequest(this.form).then(() => {
              const successMsg = this.isSameTeacher
                ? '提交成功，请等待教师审核'
                : '提交成功，请等待两位教师审核';
              this.$modal.msgSuccess(successMsg);
              this.dialogVisible = false;
              this.$emit('success');
            }).finally(() => {
              this.submitLoading = false;
            });
          }).catch(() => {});
        }
      });
    },
    /** 关闭对话框 */
    handleClose() {
      this.resetForm();
    },
    /** 重置表单 */
    resetForm() {
      this.form = {
        oldTopicId: null,
        newTopicId: null,
        changeReason: ''
      };
      this.currentTopic = null;
      this.selectedTopic = null;
      this.$refs.form && this.$refs.form.resetFields();
    }
  }
};
</script>